﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using NHibernate.Tool.hbm2ddl;
using Ornament.MVCWebFrame.Models;
using Ornament.NHibernateHelper;
using Ornament.NHibernates;
using Ornament.NHibernates.Configurations;
using Ornament.Web;
using Ornament.Web.Mvc;

namespace Ornament.MVCWebFrame.Areas.Settings.Controllers
{
    public class NHibernateController : Controller
    {
        //
        // GET: /System/NHibernate/base 0 .
        public ActionResult Index()
        {
            // find cfgFile path;
            //find session factory Name           
            string filePath = Request.MapPath("~/config/hibernate.cfg.config");
            var nh = new NHibernateSetting(filePath);
            IEnumerable<SelectListItem> sessionFactoryNames
                = from sfName in nh.GetSessionFactoryNames()
                  select new SelectListItem
                             {
                                 Text = sfName,
                                 Value = sfName
                             };
            sessionFactoryNames.First().Selected = true;
            ViewData["sessionFactoryName"] = sessionFactoryNames;
            TempData["assembly"] = nh.FindNHibernateAssembly();
            ViewData["SuggestionDriver"] = DataBaseType.SupportDataBaseTypes;
            return View(nh[sessionFactoryNames.First().Text]);
        }

        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        public ActionResult CreateTable()
        {
            try
            {
                var cc = new SchemaExport(SessionManager.Instance.Configruation);
                cc.Drop(true, true);
                cc.Create(true, true);
                (new BaseDataInit()).Build();
                var result = new ReturnResult("生成数据及表成功", true);
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new ReturnResult(ex, true), JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        public ActionResult UpdateTable()
        {
            try
            {
                var cc = new SchemaUpdate(SessionManager.Instance.Configruation);
                cc.Execute(false, true);
                
                var result = new ReturnResult("更新数据库成功.", true);
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new ReturnResult(ex, true), JsonRequestBehavior.AllowGet);
            }
        }


        /// <summary>
        /// </summary>
        /// <param name="filePath">
        /// The file path.
        /// </param>
        /// <param name="sessionFactoryName">
        /// The session factory name.
        /// </param>
        /// <param name="sessionFactory">
        /// The session factory.
        /// </param>
        /// <returns>
        /// </returns>
        [JsonContainerFilter("sessionFactory")]
        public ActionResult Save(string filePath, string sessionFactoryName, JsonContainer sessionFactory)
        {
            try
            {
                var session = new NHibernateSetting(Request.MapPath(filePath));
                SessionFactory sessionFactorySetting = session[sessionFactoryName];
                if (sessionFactory.ToBoolean("DriverInfo.ConnectionInConfig"))
                {
                    sessionFactorySetting.DriverInfo.ConnectionStringKey = sessionFactory.ToString("ConnectionStringKey");
                }
                else
                {
                    sessionFactorySetting.DriverInfo.ConnectionString =
                        sessionFactory.ToString("DriverInfo.ConnectionString");
                }

                sessionFactorySetting.DriverInfo.DataBase =
                    DataBaseType.SupportDataBaseTypes[sessionFactory.ToString("DriverInfo.DataBase.Dialect")];
                sessionFactorySetting.DriverInfo.DriverClass = sessionFactory.ToString("DriverInfo.DriverClass");

                sessionFactorySetting.Runtime.BatchSize = sessionFactory.ToInt32("Runtime.BatchSize");
                sessionFactorySetting.Runtime.Isolation =
                    (IsolationLevel)Enum.ToObject(typeof(IsolationLevel), sessionFactory.ToInt32("Runtime.Isolation"));

                sessionFactorySetting.Runtime.ShowSql = sessionFactory.ToBoolean("Runtime.ShowSql");
                sessionFactorySetting.Runtime.Timeout = sessionFactory.ToInt32("Runtime.Timeout");
                sessionFactorySetting.Runtime.UseOuterJoin = sessionFactory.ToBoolean("Runtime.UseOuterJoin");
                //Mappings
                sessionFactorySetting.Mappings.Clear();
                JsonContainer[] mappings = sessionFactory.ToArray<JsonContainer>("Mappings");
                foreach (JsonContainer item in mappings)
                {
                    Mapping mapping = sessionFactorySetting.Mappings.CreateMapping();
                    mapping.Assembly = item.ToString("Assembly");
                    sessionFactorySetting.Mappings.Add(mapping);
                }
                session.Save();
                return Json(new ReturnResult("保存成功", true), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new ReturnResult(ex, true), JsonRequestBehavior.AllowGet);
            }
        }
    }
}